package com.base.cn.platform.os.controller.user.account;

import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.pay.AlipayUtils;
import com.base.cn.platform.os.common.utils.pay.PayService;
import com.base.cn.platform.os.common.utils.pay.WeiXinUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.user.AccountStatus;
import com.base.cn.platform.os.entity.user.account.*;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.user.account.CusUserAccountBiz;
import com.base.cn.platform.os.service.user.account.CusUserCashAccountBiz;
import com.base.cn.platform.os.service.user.account.CusUserCashRecordBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 用户提现记录Controller
 *
 * @author s.li
 * @date 2018/12/01
 */
@RestController
@RequestMapping("/manage/account")
public class CusUserCashRecordController extends BaseController {

    @Autowired
    private CusUserCashRecordBiz cusUserCashRecordBiz;
    @Autowired
    private CusUserCashAccountBiz cusUserCashAccountBiz;
    @Autowired
    private CusUserAccountBiz cusUserAccountBiz;
    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 保存用户申请提现记录
     * @param userCashRecord
     * @return Map<String,Object>
     */
    @RequestMapping("/createUserCashRecord")
    public Map<String,Object> createUserCashRecord(@RequestBody CusUserCashRecord userCashRecord) throws Exception{
        if(userCashRecord.getAccountType().intValue() !=1 && userCashRecord.getAccountType().intValue() !=2){
            return ResultUtil.ERROR("提现账户类型错误");
        }
        if(userCashRecord.getAccountType().intValue() ==1){
            if(StringUtils.isEmpty(userCashRecord.getAccount())){
                return ResultUtil.ERROR("未设置支付宝提现账户");
            }
        }
        if(userCashRecord.getAccountType().intValue()==2){
            if(StringUtils.isEmpty(userCashRecord.getAccount())){
                return ResultUtil.ERROR("未绑定提现微信账号");
            }
        }
        if(userCashRecord.getPrice() <1 || userCashRecord.getPrice() > 1000){
            return ResultUtil.ERROR("每次提现必须大于等于1且小于等于1000元");
        }
        CusUserCashAccountCondition condition = new CusUserCashAccountCondition();
        condition.setUserId(userCashRecord.getUserId());
        condition.setAccount(userCashRecord.getAccount());
        condition.setAccountType(userCashRecord.getAccountType());
        CusUserCashAccount cashAccount = cusUserCashAccountBiz.findUserCashAccount(condition);
        if(ObjectUtils.isEmpty(cashAccount)){
            return ResultUtil.ERROR("提现的账号不存在");
        }
        userCashRecord.setRealName(cashAccount.getRealName());
        //用户账户对象
        CusUserAccount userAccount = cusUserAccountBiz.queryUserAccountByUserId(cashAccount.getUserId(),false);
        if(!userAccount.getAccountStatus().equals(AccountStatus.ACTIVE.toString())){
            return ResultUtil.ERROR("您的账户已被冻结，不可提现");
        }
        if(userAccount.getCashAmount().doubleValue() < userCashRecord.getPrice()){
            return ResultUtil.ERROR("账户中可提现的金额不足");
        }
        StringBuilder whereSql = new StringBuilder();
        whereSql.append(" userId = ").append(userCashRecord.getUserId());
        whereSql.append(" and DATE_FORMAT(createTime,'%Y-%m-%d') ='").append(DateUtils.format(new Date(),"yyyy-MM-dd")).append("'");
        whereSql.append(" order by `createTime` desc");
        List<CusUserCashRecord> cashRecordList = cusUserCashRecordBiz.find(whereSql.toString(),3,null);
        if(cashRecordList!=null && cashRecordList.size() ==3){
            return ResultUtil.ERROR("每天只可以进行3次提现申请");
        }else{
            if(cashRecordList!=null && !cashRecordList.isEmpty()){
                CusUserCashRecord _record = cashRecordList.get(0);
                long nowTime = System.currentTimeMillis();
                long createTime = _record.getCreateTime().getTime();
                long _t = (nowTime - createTime)/1000;
                if(_t < 60){
                    return ResultUtil.ERROR("一分钟内只可以申请提现一次");
                }
            }
        }
        cusUserCashRecordBiz.createUserCashRecord(userAccount,userCashRecord);
        return ResultUtil.SUCCESS("提现申请成功，平台运营人员将尽快核对，大概1-15个工作日内将自动转入，请注意查收");
    }

    /**
     * 分成查询用户提现记录列表
     * @param condition 查询条件
     * @param currentPage 页码
     * @param pageSize 查询数量
     * @return PageInfo<CusUserCashRecord>
     */
    @RequestMapping("/findUserCashRecordListPage")
    public PageInfo<CusUserCashRecord> findUserCashRecordListPage(@RequestBody CusUserCashRecordCondition condition,
                                                                  @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage,
                                                                  @RequestParam(value = "pageSize",required = false,defaultValue = "10") int pageSize){
        Pagination page = new Pagination();
        page.setPageSize(pageSize);
        page.setCurrentPage(currentPage);
        return cusUserCashRecordBiz.findUserCashRecordListPage(condition,page);
    }

    /**
     * 审核提现记录
     * @param id 记录ID
     * @param sysUserId 管理员ID
     * @param status 状态，2通过，3驳回
     * @param rejectText 返回原因
     * @return Map<String, Object>
     */
    @RequestMapping("/auditPass")
    public Map<String, Object> auditPass(HttpServletRequest request,
                                         @RequestParam("id") BigDecimal id,
                                         @RequestParam("sysUserId") BigDecimal sysUserId,
                                         @RequestParam("status") int status,
                                         @RequestParam(value = "rejectText",required = false) String rejectText) throws Exception{
        CusUserCashRecord cashRecord = cusUserCashRecordBiz.findById(id);
        if(ObjectUtils.isEmpty(cashRecord)){
            return ResultUtil.ERROR("提现记录不存在");
        }
        if(cashRecord.getStatus().intValue() !=1){
            return ResultUtil.ERROR("记录状态错误，审核失败");
        }
        if(status==3){
            if(StringUtils.isEmpty(rejectText)){
                return ResultUtil.ERROR("请输入驳回原因");
            }
        }
        cashRecord.setExamineUserId(sysUserId);
        if(status==2){
            cashRecord.setExamineTime(new Date());
        }
        cashRecord.setStatus(status);
        cashRecord.setRejectText(rejectText);

        if(cashRecord.getStatus().intValue()==2){//如果是通过，则转账
            PayService payService = null;
            Map<String,String> paramsData = new HashMap<>();
            TreeMap<String,String> payConfigMap = sysConfigService.getSysConfigContext(ConfigName.PAY);
            String desc = "用户提现申请";
            Map<String,Object> resultMap = null;
            if(cashRecord.getAccountType().intValue()==1){//支付宝
                if(StringUtils.isEmpty(cashRecord.getAccount())){
                    return ResultUtil.ERROR("未绑定支付宝账号");
                }
                TreeMap<String,String> infoMap = sysConfigService.getSysConfigContext(ConfigName.INFO);
                paramsData.put("account",cashRecord.getAccount());//收款方账户
                paramsData.put("amount",String.valueOf(cashRecord.getPrice()));//转账金额 单位：元
                paramsData.put("payerShowName",infoMap.get("company"));//付款方姓名
                paramsData.put("realName",cashRecord.getRealName()); //收款方真实姓名
                paramsData.put("remark",desc); //转账备注
                payService = new AlipayUtils();
            }else if(cashRecord.getAccountType().intValue()==2){//微信
                if(StringUtils.isEmpty(cashRecord.getAccount())){
                    return ResultUtil.ERROR("未绑定微信信息");
                }
                paramsData.put("openId",cashRecord.getAccount());
                paramsData.put("amount",String.valueOf(cashRecord.getPrice()));//转账金额
                paramsData.put("desc",desc);
                paramsData.put("check_name","FORCE_CHECK");
                paramsData.put("re_user_name",cashRecord.getRealName());
                payService = new WeiXinUtils();
            }
            if(payService!=null){
                resultMap = payService.payTransfer(request,payConfigMap,paramsData);
                if(ResultUtil.getSuccess(resultMap)){
                    cusUserCashRecordBiz.auditPass(cashRecord);
                }else{
                    return resultMap;
                }
            }
        }else if(cashRecord.getStatus().intValue()==3){
            cusUserCashRecordBiz.auditPass(cashRecord);
        }
        return ResultUtil.SUCCESS("审核成功");
    }
}
